<?php
namespace  app\common\service\token\driver;
use app\common\service\ServiceBase;
use app\common\service\token\TokenInterface;
use Firebase\JWT\JWT;
use think\facade\Cache;
use think\facade\Request;
use app\common\service\token\Token;
use aes\Aes;
/**
 * 后台登录的具体实现，username+password
 * 负责存储和生成
 */
class AdminToken  implements TokenInterface{

    use ServiceBase;

    /**
     * 解析adminToken
     * @param $param
     * @return mixed
     */
    public function getAccessTokenInfo($param){
        $param['user_token'] = Request::header('Access-Token');
        empty($param['user_token']) && ServiceBase::commonError(['code'=>500,'msg'=>'token不能为空',"success"=>false]);
        $key = API_KEY . JWT_KEY;
        $jwt_arr[] = JWT::urlsafeB64Encode(json_encode(['typ' => 'JWT', 'alg' => 'HS256']));
        $jwt_arr[] = Cache::get(Request::SubDomain() . "_" . $param['user_token']);
        empty($jwt_arr[1]) && ServiceBase::commonError(['code'=>500,'msg'=>'token过期',"success"=>false]);
        $jwt_arr[] = Aes::strDecrypt(urldecode($param['user_token']));
        $jwt_string = implode('.', $jwt_arr);
        $info = JWT::decode($jwt_string, $key, ['HS256']);
        time() >= $info->exp && Cache::delete(Request::SubDomain() . "_" . $param['user_token']) && ServiceBase::commonError(['code'=>500,'msg'=>'token过期',"success"=>false]);
        return $info->data;
    }


    /**
     * 生成adminToken
     * @param $param
     * @return array[]
     */
    public function createAccessToken($param){

        $where['username'] = $param['user_name'];
        $info = self::model('Admin')->getAdminInfo($where);
        empty($info) && ServiceBase::commonError(['code'=>500,'msg'=>'账号不存在',"success"=>false]);
        data_md5_key($param['password']) != $info['password'] && ServiceBase::commonError(['code'=>500,'msg'=>'密码错误，请重新输入',"success"=>false]);
        unset($info['password']);

        $info = $this->buildInfo($info);
        $key = API_KEY . JWT_KEY;
        $merchant_token = [
            "iss"  => "yiqiai",                 // 签发者
            "iat"  => TIME_NOW,                 // 签发时间
            "exp"  => TIME_NOW + 8000,          // 过期时间
            "aud"  => Request::SubDomain(),        // 接收方
            "sub"  =>Request::SubDomain(),        // 面向的用户
            "data" => $info
        ];
        $jwt_string = JWT::encode($merchant_token, $key);
        $token_array = explode('.', $jwt_string);
        $user_token = urlencode(Aes::strEncrypt(end($token_array)));
        Cache::set(Request::SubDomain() . "_" . $user_token, $token_array[1], 8000);
        unset($info['allow_link']);

        return ['data' => ['user_token' => $user_token, 'info' => $info]];
    }

    private function buildInfo($info)
    {
        ;
        $menu = $this->getMenuAuth($info);

        $info['allow_link'] = array_column($menu, 'url');
        $info['allow_menu'] = tree_data_change_key($menu, 0, false, ['name' => 'name', 'url' => 'url']);
        $info['allow_auth'] = tree_data_change_key($menu, 0, true,['name' => 'name', 'url' => 'url']);
        return $info;
    }

    /**
     * get menu auth
     * @param $info
     * @return mixed
     */
    private function getMenuAuth($info)
    {
        if ($info['leader_id'] === 0) return self::model('Menu')->getMenuList(['status' => 1, 'module' => 'admin']);

        // 获取用户组列表
        $where = ['aga.admin_id' => $info['id'], 'aga.status' => 1, 'ag.status' => 1];

        $group_list = self::model('AuthGroup')->getAdminAuthGroupList($where);
        $menu_ids = [];

        // 合并多个分组的权限节点并去重
        foreach ($group_list as $group_info)
            !empty($group_info['rules']) && $menu_ids = array_unique(array_merge($menu_ids, explode(',', trim($group_info['rules'], ','))));

        // 若没有权限节点则返回
        if (empty($menu_ids)) return $menu_ids;
        // 查询条件
        $where = [];
        $where[] = ['id', 'in', $menu_ids];
        return self::model('Menu')->getMenuList($where);
    }

    public function createSign(){

    }
}
